package com.iogogogo.activity.util;

import com.iogogogo.activity.base.Enumerator;

import java.util.*;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by tao.zeng on 2022/6/15.
 */
public interface EnumUtils {

    static Map<String, Object> toMap(Enumerator enumerator) {
        Map<String, Object> map = new HashMap<>();
        map.put(String.valueOf(enumerator.value()), enumerator.description());
        return map;
    }

    static <E extends Enum<?> & Enumerator> Map<Integer, String> toMap(Class<E> enumClazz) {
        // 合并时检查 key 是否重复
        BinaryOperator<String> merge = (u, v) -> {
            throw new IllegalStateException(String.format("Duplicate key %s", u));
        };
        Enumerator[] enumConstants = enumClazz.getEnumConstants();
        return Stream.of(enumConstants)
                .collect(Collectors.toMap(Enumerator::value,
                        Enumerator::description,
                        merge, LinkedHashMap::new));
    }

    static <E extends Enum<?> & Enumerator> Optional<E> getEnumByValue(Class<E> enumClazz, final Integer value) {
        return Stream.of(enumClazz.getEnumConstants())
                .filter(enumerator -> Objects.equals(enumerator.value(), value))
                .findAny();
    }
}
